
#include "FunctionList.h"
#include <string.h>

using namespace std;

FunctionElem::FunctionElem(Function* f) {
	Fct = f;
	Next = NULL;
}

FunctionElem::~FunctionElem() {
	if (Fct) {delete Fct;}
	if (Next) {delete Next;}
}

FunctionList::FunctionList() {
	Head = NULL;
	Current = NULL;
	Length = 0;
}

FunctionList::~FunctionList() {
	if (Head) delete Head;
}

void FunctionList::addFront(Function* f){
     FunctionElem* elem = new FunctionElem(f);
     elem->Next = Head;
     Head = elem;
     Length++;
}

bool FunctionList::isEmpty() {
     return (Head == NULL);
}

int FunctionList::getLength() {
     return Length;
}

void FunctionList::print(){
     for(FunctionElem* f = Head; f!=NULL; f = f->Next){
        f->Fct->print();
     }
}

Function* FunctionList::getFirstFunction() {
	Current = Head;
	if (Current) return Current->Fct;
	else return NULL;
}

Function* FunctionList::getNextFunction() {
	if (Current && Current->Next) {
       Current = Current->Next;
       return Current->Fct;
    }
	else return NULL;	
}

Function* FunctionList::pop() {
    Function* f = NULL;
    if (Head) {
       f = Head->Fct;
       FunctionElem* new_first = Head->Next;
       Head->Next = NULL;
       Head->Fct = NULL;
       delete Head;
       Length--;
       Head = new_first;
    }
    return f;
}

Function* FunctionList::getAndPop(string fct_name) {
     FunctionElem* pred = NULL;
     FunctionElem* succ = NULL;
     Function* fct_result = NULL;
     for (FunctionElem* e = Head ; e ;) {
         succ = e->Next;
         if (strcmp(e->Fct->FunctionName.c_str(), fct_name.c_str()) == 0) {
            fct_result = e->Fct;                                       
            if (Head == e) {
               Head = e->Next;               
            }
            else pred->Next = e->Next;
            e->Next = NULL;
            e->Fct = NULL;
            delete e;
         }
         else pred = e;
         e = succ;
     }
     return fct_result;
}
